package com.chen.controller;

import com.chen.model.Goods;
import com.chen.model.Imports;
import com.chen.service.GoodsService;
import com.chen.service.ImportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private ImportService importService;

    @RequestMapping("/goods-add")
    public String goodsAdd(){
        return "goods-add";
    }

    @RequestMapping("/addGoods")
    public String  addGoods(Goods goods){
        goodsService.addGoods(goods);
        return "success";
    }

    @RequestMapping("/findAllGoods")
    public String findAllGoods(Model model){
        List<Goods> goodsList;
        goodsList= goodsService.findAllGoods();
        model.addAttribute("goodsList",goodsList);
        return "goods-list";
    }

    @RequestMapping("/updateGoods")
    public String updateGoods(Goods goods, HttpServletRequest request){
        goods = goodsService.findGoodsById(goods.getGoods_id());
        Integer import_number = Integer.parseInt(request.getParameter("import_number"));
        Integer import_id = Integer.parseInt(request.getParameter("import_id"));
        Imports imports = importService.findImportsById(import_id);
        int number = goods.getGoods_number()+import_number;
        goods.setGoods_number(number);
        imports.setImport_state(1);
        goodsService.updateGoods(goods);
        importService.updateImports(imports);
        return "success";
    }

    @RequestMapping("/goodsUpdate")
    public String goodsUpdate(Integer goods_id,Integer import_id,Model model){
        Goods goods= goodsService.findGoodsById(goods_id);
        Imports imports = importService.findImportsById(import_id);
        model.addAttribute("goods",goods);
        model.addAttribute("imports",imports);
        return "goods-update";
    }

    @RequestMapping("/test")
    public void test(){
        Goods goods = new Goods();
//        goods.setGoods_name("牛奶");
        goods.setGoods_id(1);
        goods.setGoods_number(6660);
//        System.out.println(goods.toString());
//        goodsService.addGoods(goods);
//        List<Goods> goodsList;
//        goodsList= goodsService.findAllGoods();
//        System.out.println(goodsList.toString());
        goodsService.updateGoods(goods);
    }


//    @RequestMapping("/findAllGoods")
//    public String findAllContract(Model model){
//        List<Goods> goodList;
//        goodList = goodsService.findAllGoods();
//        for (Goods goods :goodList){
//            System.out.println(goods);
//        }
//        model.addAttribute("goodList",goodList);
//        return "goods-list";
//    }

}
